
<template>
	<view class="flex flex-direction bg-white" style="width: 100vw;height: 100vh;">
		<scroll-view class="flex flex-direction" style="height: 100%" scroll-y>
			<!-- 顶部返回按钮和分享按钮 -->
			<cu-custom bgColor="bg-white" :isBack="true">
				<block slot="content">
					<view class="flex justify-center" style="pointer-events: all;">
						<text @click="switchtab(0)" :style="{color:(current==0?'#007AFF':'#999999')}" style="font-size: 32rpx;font-weight: bold;">
							音频
						</text>
						<text @click="switchtab(1)" :style="{color:(current==1?'#007AFF':'#999999')}" style="margin-left: 48rpx;font-size: 32rpx;font-weight: bold;">
							视频
						</text>
					</view>
				</block>
				<block slot="right">
					<text class="lg text-gray cuIcon-share " @click="share()"></text>
				</block>
			</cu-custom>
			<swiper class="flex-sub" style="margin-top: 32rpx;height: 80%;" 
			@change="onSwiperchange" :current="current">
				<swiper-item style="height: 100%;">
					<scroll-view scroll-y style="height: 100%;width: 100%;">
						<view class="flex" style="padding: 0 32rpx;">
							<image :src="book.cover" mode="aspectFit" style="width: 160rpx; height: 224rpx;"></image>
							<view class="flex flex-direction justify-between" style="margin-left: 32rpx;">
								<view class="">
									<view style="font-size: 28rpx;font-weight: bold;color: #333333;">
										{{book.title}}
									</view>
									<view style="margin-top: 16rpx;font-size: 28rpx;color: #666666;">
										{{book.description}}
									</view>
								</view>
								<view style="font-size: 20rpx;color: #666666;">
									播放量{{book.viewCount}}
								</view>
							</view>
						</view>
						<view style="margin-top: 40rpx;">
							<zaudio theme="theme1"></zaudio>
						</view>
						<view v-if="bookLink" class="flex justify-between" style="margin: 0 32rpx ;padding: 32rpx 32rpx;background: #F2F8FF;border-radius: 8px;">
							<image :src="bookLink.cover" mode="aspectFit" style="width: 80rpx; height: 112rpx;"></image>
							<view class="flex flex-direction justify-between">
								<view style="width: 480rpx;font-size: 28rpx;font-weight: bold;color: #333333;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
									{{bookLink.title}}
								</view>
								<view class="flex justify-between">
									<view style="font-size: 28rpx;color: #FF3B30;">
										¥{{bookLink.price}}
									</view>
									<view style="font-size: 28rpx;color: #007AFF;">
										购买纸书&nbsp;>
									</view>
								</view>
							</view>
						</view>
						<view style="margin-top: 64rpx;padding: 0 32rpx;font-size: 32rpx;font-weight: bold;color: #1C1C1E;">
							讲书内容
						</view>
						<view style="margin-top: 36rpx;padding: 0 32rpx;">
							<!-- <rich-text :nodes="'<div>我是上瘾：让用户养成使用习惯的四大产品逻辑的讲书描述</div>'" style="line-height: 64rpx;"></rich-text> -->
							<rich-text :nodes="book.content" style="line-height: 64rpx;"></rich-text>
						</view>
						<!-- 评论 回复 -->
						<comment class="margin-left margin-right" v-if="showComment" :comment-list="commentList" type-name="讲书" @publish="handlePublish"></comment>
						
					</scroll-view>
				</swiper-item>
				<swiper-item style="height: 100%;">
					<scroll-view scroll-y style="height: 100%;width: 100%;">	
						<view v-show="!showVideo" style="position: relative;width: 100%;" >
							<image style="width: 100%;height: 400rpx;" :src="book.cover"></image>
							<image @click="play" src="../../plugin/uniapp-zaudio/static/playbtn.png" style="position: absolute;left: 50%; top: 50%; transform: translate(-50%, -50%);width:200rpx;height:200rpx;" mode=""></image>
						</view>
						<video v-show="showVideo" v-if="video" style="width: 100%;" id="myVideo" :src="video" :initial-time="startTimeVideo" @error="videoErrorCallback" @pause="handlePause" controls @timeupdate="updateTime" @loadedmetadata="videoLoaded"></video>
						<view style="margin-top: 64rpx;padding: 0 32rpx;font-size: 32rpx;font-weight: bold;color: #1C1C1E;">
							讲书内容
						</view>
						<view style="margin-top: 36rpx;padding: 0 32rpx;">
							<rich-text :nodes="book.content" style="line-height: 64rpx;"></rich-text>
						</view>
						<comment class="margin-left margin-right" v-if="showComment" :comment-list="commentList" type-name="讲书" @publish="handlePublish"></comment>
					</scroll-view>
				</swiper-item>
			</swiper>
			<!-- 底部导航栏 -->
			<view class="flex solid-top bg-white" style="width: 100%;height: 120rpx;position: fixed;bottom: 0;">
				<!-- 评论 -->
				<view class="flex-sub flex flex-direction  align-center margin-top-sm">
					<text @click="toggleMask('show')" class="text-black cuIcon-comment " style="font-size: 50rpx;"></text>
					<text>{{commentList.length}}</text>
				</view>
				<!-- 收藏 -->
				<view class="flex-sub  flex flex-direction  align-center margin-top-sm">
					<text :class="[isLike?' text-blue cuIcon-appreciatefill':'text-black cuIcon-appreciate']" @click="like()" style="font-size: 50rpx;"></text>
					<text>{{likeCount}}</text>
				</view>
				<!-- 点赞 -->
				<view class="flex-sub  flex flex-direction  align-center margin-top-sm">
					<text :class="[isFavorite?' text-blue cuIcon-likefill':'text-black cuIcon-like']" @click="favorite()" style="font-size: 50rpx;"></text>
					<text>{{favoriteCount}}</text>
				</view>
			</view>
			<!-- 占位区 -->
			<view style="width: 100%;height: 120rpx;"></view>
		</scroll-view>
		<ygc-comment ref="ygcComment"
		    :placeholder="'发布评论'" 
			@pubComment="pubComment"></ygc-comment>
		
		
		<!-- 底部弹出 分享框 -->
		<popup :type="bottom" ref="popup">
			<popup-share @close="close"></popup-share>
		</popup>
	</view>
</template>

<script>
	const TypeBook = '4';
	import zaudio from '@/plugin/uniapp-zaudio/zaudio';
	import comment from '../../components/comment/comment.vue';
	import ygcComment from '../../components/comment/ygc-comment.vue';
	import popup from '../../components/uni-popup/uni-popup.vue';
	import popupShare from '../../components/share-btn/share-btn.vue';
	import articleApi from '../../api/articleApi.js';
	import mineApi from '../../api/mineApi.js';
	export default{
		components: { 
			zaudio,
			comment,
			ygcComment,
			popup,
			popupShare
		},
		data() {
			return {
				current: 0, //swiper当前滑块
				toview: "book0",
				user: {},
				isFollow: false,
				isFavorite:false,
				isLike:false,
				favoriteCount: 0,//点赞数
				likeCount: 0,//收藏数
				bookId: this.$Route.query.id ? this.$Route.query.id : "1",
				book:{},
				bookLink: null,
				video: '',
				
				showVideo: false,
				showComment: false,
				constantID: "0000000000000000000",
				targetComment: {},
				commentList: [],
				bottom:"bottom",
				
				audiolist: this.$zaudio.audiolist, //当前音频列表
				playIndex: this.$zaudio.playIndex, //当前播放的索引
				paused: this.$zaudio.paused, //当前是否暂停
				playinfo: this.$zaudio.playinfo ,//当前播放的信息
				currentTimeAudio: 0,
				currentTimeVideo: 0,
				durationAudio: 0,
				durationVideo: 0,
			}
		},
		methods: {
			switchtab(index) {
				this.current = index;
			},
			onSwiperchange(e) {
				this.current = e.detail.current;
				if(e.detail.current == 0) {
					this.showVideo = false;
					this.videoContext.pause();
				}
			},
			videoLoaded(e) {
				this.durationVideo = e.detail.duration;
				// console.log(this.durationVideo)
			},
			play() {
				this.showVideo = true;
				this.videoContext.play();
			},
			toggleMask(type) {
				this.$refs.ygcComment.toggleMask(type);
			},
			handlePublish: function(item) {
				this.targetComment = item;
				this.toggleMask("show");
			},
			pubComment(commentContent) {
				this.$refs.ygcComment.toggleMask();
				this.$refs.ygcComment.content = '';
				let constantID = this.constantID;
				// console.log(this.targetComment)
				//向后端添加评论
				let comment = {
					userId: this.user.id,
					parentCommentId: JSON.stringify(this.targetComment) == "{}" ? constantID: (this.targetComment.parentCommentId==constantID?this.targetComment.commentId:this.targetComment.parentCommentId),
					targetCommentId: JSON.stringify(this.targetComment) == "{}" ? constantID: (this.targetComment.parentCommentId==constantID?constantID:this.targetComment.commentId),
					targetUserId: JSON.stringify(this.targetComment) == "{}" ? '' : (this.targetComment.parentCommentId==constantID?'':this.targetComment.userId),
					contentId: this.bookId,
					columnType: TypeBook,
					content: commentContent
				}
				// console.log(JSON.stringify(comment));
				articleApi.addComment(comment).then(res=>{
					this.$tip.success('评论成功!');
					this.$Router.replace({name: 'bookDetail', params:{id: this.bookId}})
				})
			},
			share() {
				this.$refs.popup.open()
			},
			favorite(){
				this.isFavorite = !this.isFavorite;
				if(this.isFavorite){	//收藏
					this.favoriteCount++;
					this.$http.post('/edu/favorite/favoriteContent', 
					{
						contentId: this.bookId,
						userId: this.user.id,
						columnType: TypeBook
					}).then(res=>{
						let data =  res.data;
						if(data.success){
							this.$tip.success(data.message)
						} else {
							this.$tip.error("收藏失败！");
							this.isFavorite = !this.isFavorite;
							this.favoriteCount--;
						}
					}).catch(err => {
						console.log(err);
						this.$tip.error("收藏失败！");
						this.isFavorite = !this.isFavorite;
						this.favoriteCount--;
					});
				} else{	//取消收藏
					this.favoriteCount--;
					this.$http.post('/edu/favorite/unfavoriteContent',
					{
						contentId: this.bookId,
						userId: this.user.id,
						columnType: TypeBook
					}).then(res=>{
						let data =  res.data;
						if(data.success){
							this.$tip.success(data.message)
						} else {
							this.$tip.error("取消收藏失败！");
							this.isFavorite = !this.isFavorite;
							this.favoriteCount++;
						}
					}).catch(err => {
						console.log(err);							
						this.$tip.error("取消收藏失败！");
						this.isFavorite = !this.isFavorite;
						this.favoriteCount++;
					});
				}
			},
			like(){
				this.isLike = !this.isLike
				if(this.isLike){	//点赞
					this.likeCount++;
					this.$http.post('/edu/like/likeContent', 
					{
						contentId: this.bookId,
						userId: this.user.id,
						columnType: TypeBook
					}).then(res=>{
						let data =  res.data;
						if(data.success){
							this.$tip.success(data.message)
						} else {
							this.$tip.error("点赞失败！");
							this.isLike = !this.isLike
							this.likeCount--;
						}
					}).catch(err => {
						console.log(err);
						this.$tip.error("点赞失败！");
						this.isLike = !this.isLike
						this.likeCount--;
					});
				} else{	//取消点赞
					this.likeCount--;
					this.$http.post('/edu/like/dislikeContent',
					{
						contentId: this.bookId,
						userId: this.user.id,
						columnType: TypeBook
					}).then(res=>{
						let data =  res.data;
						if(data.success){
							this.$tip.success(data.message)
						} else {
							this.$tip.error("取消点赞失败！");
							this.isLike = !this.isLike
							this.likeCount++;
						}
					}).catch(err => {
						console.log(err);
						this.$tip.error("取消点赞失败！");
						this.isLike = !this.isLike
						this.likeCount++;
					});
				}
			},
			close(){
				this.$refs.popup.close()
			},
			videoErrorCallback: function(e) {
				console.log("video play error");
			},
			handlePause(e) {
				console.log("pause");
			},
			updateTime(e) {
				this.currentTimeVideo = e.detail.currentTime;
				// console.log("video time", this.currentTimeVideo)
			},
		},
		onLoad() {
			this.user.id = this.$store.getters.userid;
			if(!this.bookId || this.bookId==''){
				this.bookId = '1';
			} 
			// console.log("bookId", this.bookId);
			this.$http.get("/edu/book/getBookAudioDetail/" + this.bookId + "/" + this.user.id).then(res=>{
				let data = res.data;
				// console.log("audio data", data.result);
				if(data.success) {
					this.book = data.result;
					this.book.content = this.book.content.replace(/<img[^>]*>/gi,function(match,capture){
						match = match.replace("img","img style=\"width:100%\"")
						return match
					})
					let audiolist = this.$zaudio.audiolist;
					audiolist.push({src: this.book.audio});
					this.$zaudio.setAudio(audiolist); //添加音频
					this.$zaudio.setRender(audiolist.length - 1);//渲染第一首音频
					this.$zaudio.operate(audiolist.length - 1);
					// console.log("book.currentTime", this.book.currentTime)
					if(this.book.currentTime) {
						this.$zaudio.seek(this.book.currentTime);
					} else {
						this.$zaudio.seek(0);
					}
					this.$zaudio.operate(audiolist.length - 1);
					this.isLike = data.result.isLike;
					this.isFavorite = data.result.isFavorite;
					this.likeCount = data.result.likeCount;
					this.favoriteCount = data.result.favoriteCount;
				}
			})
			this.$http.get("/edu/book/getBookBuyLink/" + this.bookId).then(res=>{
				let data = res.data;
				if(data.success) {
					this.bookLink = data.result;
				} else {
					this.bookLink = null;
				}	
			})

			this.$http.get("/edu/book/getBookVideoDetail/" + this.bookId + "/" + this.user.id).then(res=>{
				let data = res.data;
				if(data.success) {
					this.video = data.result.video;
					this.startTimeVideo = data.result.currentTime;
				}
			})
			this.targetComment = {};
			articleApi.getArticleComment([this.bookId, TypeBook]).then(res=>{
				this.commentList = res.data;
				this.showComment = true;
			})
		},
		onUnload() {
			this.$zaudio.syncStateOff('page-index-get-state')
			//更新音频学习记录
			this.$http.post("/edu/learn-record/updateLearnRecord", {
				"authorId": null,	//todo
				"columnType": TypeBook,
				"contentId": this.bookId,
				"contentSubject": "audio",
				"currentTime": this.currentTimeAudio,
				"totalTime": this.durationAudio,
				"learnedTime": this.currentTimeAudio,
				"userId": this.user.id
			}).then(res => {
				let data = res.data;
				if (!data.success) {
					console.log("更新音频学习记录失败")
				}
			})
			//更新视频学习记录
			this.$http.post("/edu/learn-record/updateLearnRecord", {
				"authorId": null,	//todo
				"columnType": TypeBook,
				"contentId": this.bookId,
				"contentSubject": "video",
				"currentTime": this.currentTimeVideo,
				"totalTime": this.durationVideo,
				"learnedTime": this.currentTimeVideo,
				"userId": this.user.id
			}).then(res => {
				let data = res.data;
				if (!data.success) {
					console.log("更新视频学习记录失败")
				}
			})
			this.$zaudio.stop();
			this.$zaudio.setAudio([]);
		},
		onShow() {
			//实时渲染当前的播放状态
			this.$zaudio.syncRender()
			//实时获取当前播放状态
			this.$zaudio.syncStateOn('page-index-get-state', ({ audiolist, playIndex, paused, playinfo }) => {
				this.audiolist = audiolist;
				this.playIndex = playIndex;
				this.paused = paused;
				this.playinfo = playinfo;
				// console.log("playinfo", this.playinfo)
				this.currentTimeAudio = playinfo.current_value;
				this.durationAudio = playinfo.duration_value;
				// console.log(this.currentTimeAudio)
			});
		},
		onHide(){
			//卸载page-index-get-state,提高页面性能
			this.$zaudio.syncStateOff('page-index-get-state')
		},
		onReady: function(res) {
			// #ifndef MP-ALIPAY
			this.videoContext = uni.createVideoContext('myVideo', this);
			// #endif
		},
	}
</script>

<style>
</style>

